package com.it.tydic.estate.common.security;

import com.it.tydic.estate.module.model.inner.TbUser;
import com.it.tydic.estate.module.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Configuration
@EnableWebSecurity
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserService userService;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       //取得用户
        TbUser user = userService.findByUserName(username);
        if (user == null) {
            throw new UsernameNotFoundException("UserName " + username + " not found");
        }
        Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(user.getUserId());
        MyPasswordEncoder passwordEncoder =new MyPasswordEncoder();

        	 org.springframework.security.core.userdetails.User userDetail =
                     new org.springframework.security.core.userdetails.
                             User(user.getUserName(),user.getUserPassward(),
        			  true,//是否可用
                      true,//是否过期
                      true,//证书不过期为true
                      true,//账户未锁定为true ,
                     grantedAuths);
             return userDetail;
        }

    // 取得用户的权限
    private Set<GrantedAuthority> obtionGrantedAuthorities(String userId) {
        Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
        List<String> roleIds= userService.findRolesByUserId(userId);
        for(String roeId: roleIds){
            authSet.add(new SimpleGrantedAuthority(roeId));
        }
        return authSet;
    }
}
